package com.yuanchu.order.listener;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.yuanchu.messages.service.MqMessageService;
import com.yuanchu.order.entity.YoshopOrderEntity;
import com.yuanchu.order.service.YoshopOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Instant;
import java.util.Map;

/**
 * @version: 1.0
 * @Author: adan
 * @description:
 * @date: 2024-02-23 17:08
 */
@Slf4j
@Component
public class OrderListener {


    @Resource
    private MqMessageService mqMessageService;

    @Resource
    private YoshopOrderService orderService;


    // 监听消息队列接收支付结果通知
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "paynotify_order_queue"),
            exchange = @Exchange(name = "paynotify_order_direct"),
            key = {"order.status"}
    ))
    public void listenOrderStatusQueue(String msg) {
        // 接收到消息
        log.info("消费者接收到paynotify_order_queue的消息：【{}】", msg);
        Map map = JSON.parseObject(msg, Map.class);
        String orderId = map.get("orderId").toString();
        Integer payStatus = Integer.valueOf(map.get("payStatus").toString());

        boolean update = orderService.update(new UpdateWrapper<YoshopOrderEntity>().eq("order_id", orderId)
                .set("pay_status", payStatus)
                .set("pay_time", 0)
                .set("update_time", String.valueOf(Instant.now().toEpochMilli() / 1000))
        );

        if (!update) {
            log.info("更新订单状态失败！");
            mqMessageService.addMessage("更新订单状态失败: paynotify_order_queue", orderId, msg, null);
        }
        log.info("消息处理完成！");
    }


}
